package net.edu_soft.ec.common.shiro;

import net.edu_soft.ec.asset.pojo.UserInfo;
import net.edu_soft.ec.asset.pojo.bo.PermissionBO;
import net.edu_soft.ec.asset.pojo.bo.UserPermission;
import net.edu_soft.ec.asset.service.UserInfoService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;


public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserInfoService userService;

    /*
     * 认证（登录）
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        // 得到用户账号
        String username = usernamePasswordToken.getUsername();
        System.out.println("realm ---- username: " + username);
        // 查询用户信息
        UserInfo user = userService.findByUserName(username);
        if (user == null) {
            return null;
        }
        // 当前realm对象的name
        String realmName = getName();
        //加密密码
        //password = CustomUtil.getMD5Value(password, "puing");
        //user.setPassword(password);
        this.setSession("userInfo", user);
        System.out.println("realm ----user: " + user);
        // 盐值
        ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());
        // 封装用户信息，构建AuthenticationInfo对象并返回
        AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user, user.getPassword(),
                credentialsSalt, realmName);
        return authcInfo;
    }

    /*
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 从session中得到user
        UserInfo user = (UserInfo) principals.getPrimaryPrincipal();
        System.out.println("用户信息："+user);
        UserPermission userPermission = null;
		List<PermissionBO> ups = null;
        System.out.println("权限1："+userPermission);
		if (user != null) {
			//根据当前用户查询角色
			userPermission = userService.selPermission(user.getRoleId());
            System.out.println("权限2："+userPermission);
            // 提取权限
            ups = userPermission.getPermissions();
        }
        // 定义权限集合
        List<String> permissionList = new ArrayList<>();
        // 判断是否存在
        if (userPermission != null) {
            if (ups.size() > 0) {
                // 遍历提取权限并添加进集合
                for (PermissionBO permission : ups) {
                    permissionList.add(permission.getPerCode());
                }
            }

        }
        // 创建鉴权对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 将角色名添加进对象
        info.addRole(userPermission.getName());
        // 将权限集合添加进对象
        info.addStringPermissions(permissionList);
        return info;
    }

    /**
     * 将一些数据放到ShiroSession中,以便于其它地方使用
     * 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到
     */
    private void setSession(Object key, Object value) {
        Subject currentUser = SecurityUtils.getSubject();
        if (null != currentUser) {
            Session session = currentUser.getSession();
            System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");
            System.out.println("Session是[" + session.getId() + "]");
            if (null != session) {
                session.setAttribute(key, value);
            }
        }
    }

}
